<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>My WebSocket</title>
</head>

<body>
<input id="text" type="text"/>
<button onclick="send()">Send</button>
<button onclick="close()">Close</button>
<div id="message"></div>
</body>

<script type="text/javascript">
    let websocket = null;

    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        // websocket = new WebSocket("ws://localhost:8080/oneToService"); // 客户端-服务端通信模式启用
        websocket = new WebSocket("ws://localhost:8080/oneToOne"); // 客户端-客户端一对一通信模式启用
        // websocket = new WebSocket("ws://localhost:8080/oneToMany"); // 客户端-客户端一对多通信模式启用

        //发生错误时
        websocket.onerror = function () {
            setMessageInnerHTML("error");
        };

        //成功建立连接时
        websocket.onopen = function (event) {
            setMessageInnerHTML("open");
        }

        //接收到消息时
        websocket.onmessage = function (event) {
            setMessageInnerHTML(event.data);
        }

        //关闭连接时
        websocket.onclose = function () {
            setMessageInnerHTML("close");
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            websocket.close();
        }
    } else {
        alert('很遗憾，您的浏览器不支持WebSocket！')
    }

    //显示服务器端返回的消息
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭连接按钮
    function close() {
        websocket.close();
    }

    //发送消息按钮
    function send() {
        const message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>
